package com.bdk.middle.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdk.middle.common.domain.PageDO;
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.util.BeanUtilsExtends;
import com.bdk.middle.common.util.Constant;
import com.bdk.middle.common.util.DateUtil;
import com.bdk.middle.goods.api.domain.GoodsCategoryDO;
import com.bdk.middle.goods.api.query.GoodsCategoryQueryDO;
import com.bdk.middle.goods.core.entity.GoodsCategoryEntity;
import com.bdk.middle.goods.core.mapper.GoodsCategoryMapper;
import com.bdk.middle.goods.service.GoodsCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2021-03-18
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategoryEntity> implements GoodsCategoryService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Override
    public ResultDO add(GoodsCategoryDO domain) {

        GoodsCategoryEntity entity = new GoodsCategoryEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        result = getCode(domain.getCategoryId());

        if(!result.isSuccess()) {
            return result;
        }
        entity.setCode((String) result.getModel(ResultDO.FIRST_MODEL_KEY));
        int res = -1;
        try {
            res = goodsCategoryMapper.insert(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_CATEGORY_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_CATEGORY_ADD_ERROR.getCode() + " msg" + ErrorCode.GOODS_CATEGORY_ADD_ERROR.getMsg());
            return result;
        }

        return result;
    }

    private ResultDO getCode(String categoryId) {
        ResultDO result = new ResultDO();
        if(StringUtils.isEmpty(categoryId)) {
            List<GoodsCategoryEntity> list = null;
            try {
                list = goodsCategoryMapper.selectList(Wrappers.<GoodsCategoryEntity>lambdaQuery().eq(GoodsCategoryEntity::getCategoryId, "0").orderByAsc(GoodsCategoryEntity::getCode));
            } catch(Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }
            int code = 10;
            if(list.size() != 0) {
                GoodsCategoryEntity entity = list.get(list.size() - 1);
                code = Integer.parseInt(entity.getCode());
                code = code + 10;
            }
            result.setModel(ResultDO.FIRST_MODEL_KEY, code +"");
        } else {
            GoodsCategoryEntity entity = null;
            try {
                entity = goodsCategoryMapper.selectOne(Wrappers.<GoodsCategoryEntity>lambdaQuery().eq(GoodsCategoryEntity::getId, categoryId));
            } catch(Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }

            int count = 0;
            try {
                count = goodsCategoryMapper.selectCount(Wrappers.<GoodsCategoryEntity>lambdaQuery().eq(GoodsCategoryEntity::getCategoryId, categoryId));
            } catch(Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }

            String code = "";
            if(count == 0 ) {
                code = entity.getCode() + "10";
            } else {
                code = entity.getCode() + (10 + count);
            }
            result.setModel(ResultDO.FIRST_MODEL_KEY, code);
        }

        return result;
    }


    @Override
    public ResultDO edit(GoodsCategoryDO domain) {

        GoodsCategoryEntity entity = new GoodsCategoryEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());

        int res = -1;
        try {
            res = goodsCategoryMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_CATEGORY_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_CATEGORY_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_CATEGORY_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO get(String id) {
        ResultDO result = new ResultDO();

        GoodsCategoryEntity entity = null;

        try {
            entity = goodsCategoryMapper.selectById(id);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        GoodsCategoryDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO remove(String id) {

        ResultDO result = new ResultDO();

        int res = -1;
        try {
            res = goodsCategoryMapper.deleteById(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_CATEGORY_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_CATEGORY_DELETE_ERROR.getCode() + " msg" + ErrorCode.GOODS_CATEGORY_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO find(GoodsCategoryQueryDO query) {

        ResultDO result = new ResultDO();

        QueryWrapper<GoodsCategoryEntity> wrapper = new QueryWrapper<>();

        if(StringUtils.isNotEmpty(query.getAppId())) {
            wrapper.eq("app_id", query.getAppId());
        }
        if(StringUtils.isNotEmpty(query.getCategoryId())) {
            wrapper.eq("category_id", query.getCategoryId());
        }
        if(StringUtils.isNotEmpty(query.getCode())) {
            wrapper.likeRight("code", query.getCode());
        }
        if(StringUtils.isNotEmpty(query.getName())) {
            wrapper.like("name", query.getName());
        }
        Page<GoodsCategoryEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<GoodsCategoryEntity> iPage = null;
        try {
            iPage = goodsCategoryMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsCategoryDO> doList = getDomainList(iPage.getRecords());

        PageDO<GoodsCategoryDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private GoodsCategoryDO getDomain(GoodsCategoryEntity entity) {
        ResultDO result = new ResultDO();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        GoodsCategoryDO domain = new GoodsCategoryDO();
        DateUtil.dateToString(entity.getCreateDate(), DateUtil.DATE_FORMAT);
        DateUtil.dateToString(entity.getModifiDate(), DateUtil.DATE_FORMAT);
        if(!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }


    private List<GoodsCategoryDO> getDomainList(List<GoodsCategoryEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<GoodsCategoryDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(GoodsCategoryEntity entity : list) {

                GoodsCategoryDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
